import java.util.LinkedList;


public class Game 
{
	public static GamePlay gamePlay;
	
	public static int WIDTH,HEIGHT;
	private Ball[] balls;private long ticks;
	private LinkedList<Floor> floors;
	private FloorGenerator floorGenerator;
	private static MoveHandler moveHandler;
	private int floorsPassed;
	private boolean over;
	private int numPlayers;
	
	public Game(GamePlay gp, int numPlayers)
	{
		Game.gamePlay = gp;
		this.numPlayers = numPlayers;
		init();
	}
	
	public void init()
	{
		Game.WIDTH = gamePlay.getBlockWidth() * gamePlay.getNumBlocks();
		Game.HEIGHT = gamePlay.getHeight();
		balls = new Ball[numPlayers];
		int gap = Game.WIDTH / (numPlayers + 1);
		for (int i=0; i<numPlayers; i++)
		{
			balls[i] = new Ball(gap*(i+1) - gamePlay.getBallWidth()/2,Game.HEIGHT-50, gamePlay.getBallWidth(), gamePlay.getBallHeight());
		}
		ticks = 0;
		floors = new LinkedList<Floor>();
		floorGenerator = new FloorGenerator(this);
		moveHandler= new MoveHandler(this,balls,floors);
		floorsPassed=0;
	}
	
	public void update()
	{
		for(Ball b:balls)
			b.update();
		
		for(Floor f : floors)
		{
			f.update();
		}
		floorGenerator.update();
		removeOldFloors();
		
		//TODO change stop condition !
		for (int i=0; i<balls.length; i++)
		{
			if(balls[i].getY()>HEIGHT)
				over=true;
		}
		ticks++;
	}
	
	private void removeOldFloors()
	{
		while(! floors.isEmpty())
		{
			if(floors.getFirst().getY() > Game.HEIGHT)
			{
				floors.removeFirst();
				floorsPassed++;
			}
			else
				break;
		}
	}
	

	public long getTicks() {
		return ticks;
	}
	
	public void add(Floor f)
	{
		floors.addLast(f);
	}
	
	public static MoveHandler getMoveHandler()
	{
		return moveHandler;
	}

	public Ball[] getBall() {
		return balls;
	}

	public LinkedList<Floor> getFloors() {
		return floors;
	}

	public int getFloorsPassed() {
		return floorsPassed;
	}

	public boolean isOver() {
		return over;
	}
	
	public int getLevel()
	{
		return floorGenerator.getLevel();
	}
}
